package com.zyz.bookborrowing.filter;

import com.zyz.bookborrowing.utils.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 拦截所有的请求，判断当前是否是登录后状态，如果是就访问，不是的话就跳转回登录界面
 */
@WebFilter(filterName = "authenticationFilter", urlPatterns = "/*")
public class AuthenticationFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
//        显示都有哪些受到了拦截
//        System.out.println(request.getRequestURI());
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login.jsp") || requestURI.contains("loginServlet")
                || requestURI.contains(".css") || requestURI.contains("/js/") || requestURI.contains("/images/")){
//            只要包含 "login.jsp" 字符串，就放过
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
//        其它情况就需要判断是否是登录的状态
            HttpSession session = request.getSession();
//        取出来存放的user信息
            Object attribute = session.getAttribute(Constant.SERVLET_LOGIN_USER);
            if (attribute != null) {
//            有用户信息就放过
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
//            说明没有登录，跳转回登录界面
                session.setAttribute("msg", "请先登录");
                response.sendRedirect("/login.jsp");
            }
        }

    }

    @Override
    public void destroy() {}
}
